import re

# from django import http
from django import http
from django.contrib.auth import login
from django.shortcuts import render, redirect

# Create your views here.
from django.urls import reverse
from django.views import View

from apps.users.models import User
import logging

logger = logging.getLogger('django')
# Create your views here.
class RegisterView(View):

    def get(self,request):

        return render(request,'register.html')

    def post(self,request):
       username = request.POST.get('username')
       password = request.POST.get('password')
       password2 = request.POST.get('password2')
       mobile = request.POST.get('mobile')
       allow = request.POST.get('allow')
       # 2.数据的验证(我们不相信前端提交的任何数据)
       #     2.1 验证必传(必须要让前端传递给后端)的数据是否有值
       # all([el,el,el]) el必须有值 只要有一个为None 则为False
       if not all([username,password,password2,mobile]):
           return http.HttpResponseBadRequest('参数有问题')
       #     2.2 判断用户名是否符合规则 判断 5-20位 数字 字母 _
       if not re.match(r'[0-9a-zA-Z_]{5,20}', username):
           return http.HttpResponseBadRequest('用户名不合法')
       #     2.3 判断密码是否 符合规则
       if not re.match(r'[0-9a-zA-Z_]{8,20}', password):
           return http.HttpResponseBadRequest('密码不合法')
       #     2.4 判断确认密码和密码是否一致
       if password != password2:
           return http.HttpResponseBadRequest('密码不一致')
       #     2.5 判断手机号是否符合规则
       if not re.match(r'1[3-9]\d{9}', mobile):
           return http.HttpResponseBadRequest('手机号不符合规则')
       # 2.6 验证同意协议是否勾选

       # 3.验证数据没有问题才入库
       # 当我们在操作外界资源(mysql,redis,file)的时候,我们最好进行 try except的异常处理
       # User.objects.create  直接入库 理论是没问题的 但是 大家会发现 密码是明文
       try:
           user = User.objects.create_user(username=username, password=password, mobile=mobile)
       except Exception as e:
           logger.error(e)
           return render(request, 'register.html', context={'error_message': '数据库异常'})
           return http.HttpResponseBadRequest('数据库异常')

       # 4.返回响应, 跳转到首页

       # 注册完成之后,默认认为用户已经登陆了
       # 保持登陆的状态
       # session
       # 自己实现request.session

       # 系统也能自己去帮助我们实现 登陆状态的保持
       from django.contrib.auth import login
       login(request, user)

       return redirect(reverse('contents:index'))
       # return http.HttpResponse('注册成功')



class UsernameCountView(View):
    def get(self,request,username):
        try:
            count = User.objects.filter(username=username).count()
        except Exception as e:
            logger.error(e)
            return http.JsonResponse({'code':400,'errmsg':'数据库异常'})

        return http.JsonResponse({'code':0,'count':count})


class MobileCountView(View):
    def get(self,request,mobile):
        try:
            count = User.objects.filter(mobile=mobile).count()
        except Exception as e:
            logger.error(e)
            return http.JsonResponse({'code':400,'errmasg':'数据库异常'})

        return http.JsonResponse({'code':0,'count':count})

# 用户登录：
# post  login/
# requestbody:username、password
# 接收数据，检查数据格式，验证，登录到主页，状态保持
class LoginView(View):
    def get(self,request):

        print('heihei')
        return render(request,'login.html')

    def post(self,request):
        username = request.POST.get('username')
        password = request.POST.get('password')
        remembered = request.POST.get('remembered')

        if not all([username,password]):
            return http.HttpResponseBadRequest('缺少必要的参数')
        if not re.match(r'^[a-zA-Z0-9_]{5,20}$',username):
            return http.HttpResponseBadRequest('用户名错误')
        if not re.match(r'^[0-9A-Za-z]{8,20}$',password):
            return http.HttpResponseBadRequest('密码错误')

#         验证数据有两种方法：
#           1、使用django的认证后端
#           2、自己查询数据库（根据用户名、手机号查询对应的user用户，再比对密码
        from django.contrib.auth import authenticate
        # 默认的后端是调用了from django.contrib.auth.backends import ModelBackend
        # ModelBackenc中的方法
        # def authenticate(self,request,username=None,password=None,**kwargs)

        # 如果用户名和密码正确，则返回user
        # 否则返回None
        user = authenticate(username=username,password=password)

        # 如果验证成功则登录，状态保持
        if user is not None:
            login(request,user)

            # 记住登陆
            if remembered == 'on':
                request.session.set_expiry(30*24*3600)
            else:
                request.session.set_expiry(0)

            return redirect(reverse('contents:index'))
        else:
            return render(request,'login.html',context={'account_errmsg':'用户名或密码错误'})

